package mapper.loader;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import mapper.base.IPlugin;
import mapper.config.MapperApiConfigure;
import mapper.context.AppContext;
import mapper.context.PluginContext;
import mapper.model.PluginInfo;
import mapper.utils.ClassLoaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.MalformedURLException;
import java.util.List;

@Data
@Slf4j
@Component
public class PluginLoader {

	@Autowired
	private MapperApiConfigure mapperApiConfigure;

	@Autowired
	private AppContext appContext;

	@Autowired
	private PluginContext pluginContext;

	public void load() {
		List<PluginInfo> plugins = mapperApiConfigure.getPlugins();
		for(PluginInfo pluginInfo : plugins) {
			if(null==pluginInfo.getName() || "".equals(pluginInfo.getName().trim())) {
				log.error("Must to be set plugin name." + pluginInfo.getName());
				continue;
			}
			if(null==pluginInfo.getClassloaderPath() || "".equals(pluginInfo.getClassloaderPath().trim())) {
				log.error("Must to be set the classloader path for plugin " + pluginInfo.getName());
				continue;
			}

			File jarFile = getPluginFile(pluginInfo.getName());
			if(!jarFile.exists()) {
				log.error("Can not find jar file for plugin " + pluginInfo.getName());
				continue;
			}

			try {
				ClassLoader classLoader = ClassLoaderUtil.getClassLoader(jarFile);
				Class<?> clazz = classLoader.loadClass(pluginInfo.getClassloaderPath());
				appContext.registerBean(clazz.getName(), clazz);
				IPlugin plugin = (IPlugin)appContext.getBean(clazz.getName());
				pluginContext.register(pluginInfo, plugin);
				log.info("Success load plugin " + pluginInfo.getName());
			} catch (ClassNotFoundException | MalformedURLException e) {
				log.error(String.format("Fail to loading plugin %s: \r\n, class: %s, path: %s",
						pluginInfo.getName()), pluginInfo.getClassloaderPath(), jarFile.getAbsolutePath(), e);
			}
		}
	}

	private File getPluginFile(String pluginName) {
		pluginName = pluginName.replace(".", "").replace("\\", "").replace("/", "");
		//tomcat路径
		String property = System.getProperty("catalina.home");
		String path =property + File.separator + "plugins" + File.separator + pluginName + ".jar";
		File file = new File(System.getProperty("user.dir") + File.separator + pluginName + File.separator + "target" + File.separator + pluginName + ".jar");
		if (file.exists()) {
			return file;
		}
		else {
			file = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + pluginName + ".jar");
		}

		if(file.exists()) {
			return file;
		}
		else {
			new File(path);
		}
		return file;
	}
}
